/**
 * @description 现金流预测
 * @author wangjianjun
 */

import React, { PureComponent } from 'react';
import { DATA_ENTRY, AdvancedSearch, ContentPackage, QuickQueryC, XYAxisChartsC, TableC, NoQueryC, SecondHeaderC } from '../../../comps';
import { fixedNum } from '../../../utils/utils';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, message, Divider } from 'antd';
import { connect } from 'dva';
import style from './index.less';
import moment from 'moment';
import 'moment/locale/zh-cn';
import imgURL from '../../../assets/busi/portfolioBuild/cashManage/cash_bg.png';
import uuid from 'es6-uuid';

@Form.create()
@connect(({ forecast, loading, globalM, keyFiguresM }) => ({ forecast, loading, globalM, keyFiguresM }))
export default class Forecast extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      noQuery: true,
      search: {}, //查询条件存储
      columns: undefined, //频率的统计值表格数据
      dataSource: undefined,
      columnsCash: undefined, //现金流表格数据
      dataSourceCash: undefined,
      pageInfoCash: {},
      currentPage: 1, //当前页
      numInPage: 20, //每页数量
      total: 0,
      current: 1,
      pageSize: 20,
      xAxis: undefined, //bar图表数据
      series: undefined,
      disabled: [], //设置 月 季 年禁止
      frequency: 'month', //设置 月 季 年选择项
      checkEventType: '0',
      selInit1: [
        {
          value: '0',
          title: '全部',
          children: [
            { value: 'DQ', title: '付息' },
            { value: 'FX', title: '到期' },
            { value: 'HB', title: '还本' },
          ],
        },
      ],
      selInit2: [
        { value: '1', title: '行权' },
        { value: '2', title: '到期' },
        { value: '3', title: '推荐' },
      ],
      equityProductCode: undefined,
    };
  }

  componentDidMount() {}
  UNSAFE_componentWillReceiveProps() {
    //从用户视图跳转过来
    let data = sessionStorage.getItem('forecast');
    sessionStorage.removeItem('forecast');
    if (data) {
      let riseFallProduct = JSON.parse(data);
      //查询变量赋值 以及表单赋值
      this.product.props.form.setFieldsValue({
        portfolioId: [riseFallProduct.portfolioId],
        weightSetting: riseFallProduct.weightSetting,
      });
      this.setState(
        {
          equityProductCode: riseFallProduct.productCode,
        },
        () => {
          this.getSearchData({
            beginDate: moment(),
            endDate: moment().add(1, 'year'),
            eventType: '0',
            // 修改成组合id
            portfolioId: [riseFallProduct.portfolioId],
            weightSetting: riseFallProduct.weightSetting,
          });
        },
      );
    }
  }

  componentWillUnmount() {}
  //拿图表数据
  getAllDate(value, type) {
    const { dispatch } = this.props;
    //如果是全部，需要转换
    if (value && value.eventType && value.eventType == '0') {
      value.eventType = ['DQ', 'FX', 'HB', 'XQ'];
    }
    //时间需要转换
    if (value && value.beginDate && value.endDate) {
      value.beginDate = moment(value.beginDate).format('YYYYMMDD');
      value.endDate = moment(value.endDate).format('YYYYMMDD');
    }

    //设置undefined,出现loading效果
    this.setState({
      xAxis: undefined,
      series: undefined,
      columns: undefined,
      dataSource: undefined,
    });

    dispatch({
      type: 'forecast/netCash',
      payload: {
        ...value,
      },
      callback: (data) => {
        let newSeries = [];
        data.series[0].data.map((item) => {
          newSeries.push(Number(item).toFixed(4));
        });

        let series = [
          {
            name: '净现金流',
            data: newSeries,
          },
        ];

        this.setState({
          xAxis: data.xAxis,
          series: series,
        });
      },
    });

    dispatch({
      type: 'forecast/frequencyCount',
      payload: {
        ...value,
      },
      callback: (data) => {
        data.dataSource.map((item, index) => {
          item.key = index;
        });
        this.setState({
          columns: data.columns,
          dataSource: data.dataSource,
        });
      },
    });
    // 获取汇总信息
    dispatch({
      type: 'forecast/getAccount',
      payload: {
        ...value,
      },
    });

    if (type != 'frequencyChange') {
      this.setState({
        columnsCash: undefined,
        dataSourceCash: undefined,
      });
      dispatch({
        type: 'forecast/cashFlowDetails',
        payload: {
          ...value,
        },
        callback: (data) => {
          data.dataSource.map((item, index) => {
            item.key = uuid(10);
          });
          this.setState({
            columnsCash: data.columns,
            dataSourceCash: data.dataSource,
            total: data.pageInfo.total,
          });
        },
      });
    }
  }

  //点击查询按钮刷新数据
  getSearchData = (e) => {
    const p = this.product.props.form.getFieldsValue();
    console.log(111111, e, p);
    const { dispatch } = this.props;
    const { numInPage, frequency } = this.state;
    //不就行操作如果查询条件不完整,提示用户，并且不就行任何操作
    if (!(e.eventType && e.beginDate && e.endDate && e.portfolioId && e.weightSetting)) {
      message.warning('请设置完整的查询条件！');
      return;
    }

    //查询的时候控制 月季年 按钮disable

    //加一个季度
    let oneQuarter = moment(e.beginDate).add(3, 'month').subtract(1, 'day').format('YYYYMMDD');
    //加一年
    let oneYear = moment(e.beginDate).add(1, 'year').subtract(1, 'day').format('YYYYMMDD');
    //最后一天
    let lastday = moment(e.endDate).format('YYYYMMDD');
    let quar1 = lastday - oneQuarter < 0 ? true : false;
    let quar2 = lastday - oneYear < 0 ? true : false;
    if (quar1) {
      this.setState({
        disabled: ['quarter', 'year'],
      });
    } else if (quar2) {
      this.setState({
        disabled: ['year'],
      });
    } else {
      this.setState({
        disabled: [],
      });
    }

    this.setState({
      currentPage: 1,
      search: e,
      frequency: 'month', //点击查询默认“月”
      noQuery: false, //点击查询后去掉noQuery图片，到正常状态
    });
    const value = {
      numInPage: numInPage,
      currentPage: 1,
      frequency: 'month',
      ...e,
    };
    this.getAllDate(value);
  };

  //点击重置按钮,清空搜索条件
  onClear = (e) => {
    this.setState({
      search: {},
    });
  };

  //显示频率切换
  frequencyChange = (e) => {
    const { numInPage, frequency, search } = this.state;
    //不就行操作如果查询条件不完整,提示用户，并且不就行任何操作
    if (!(search.eventType && search.beginDate && search.endDate && search.portfolioId && search.weightSetting)) {
      message.warning('请设置完整的查询条件！');
      return;
    }
    this.setState(
      {
        frequency: e,
        currentPage: 1,
      },
      () => {
        const value = {
          numInPage: numInPage,
          currentPage: 1,
          frequency: this.state.frequency,
          ...search,
        };
        this.getAllDate(value, 'frequencyChange');
      },
    );
  };

  //分页
  onShowSizeChange = (current, size) => {
    this.setState({
      current: 1,
      pageSize: size,
    });
  };

  onPageChange = (page, pageSize) => {
    this.setState({
      current: page,
    });
  };

  render() {
    const {
      forecast: { accountData },
      globalM: { dataDictionary: selectData },
      keyFiguresM: { riseFallProduct },
    } = this.props;
    const { columns, columnsCash } = this.state;
    //组装字典数据
    let selInit1 = [];
    let selInit2 = [];
    if (selectData && selectData.CASHFLOW_EVENTTYPE && selectData.CASHFLOW_WEIGHTSET) {
      selectData.CASHFLOW_WEIGHTSET.map((item) => {
        let data1 = {};
        data1.value = item.code;
        data1.title = item.value;
        selInit2.push(data1);
      });
      selectData.CASHFLOW_EVENTTYPE.map((item) => {
        let data2 = {};
        data2.value = item.code;
        data2.title = item.value;
        selInit1.push(data2);
      });
    }
    let selInit = [
      {
        value: '0',
        title: '全部',
        children: selInit1,
      },
    ];

    //组装columns
    if (columns) {
      columns.map((item, key) => {
        if (item.key == 'inflowAmt' || item.key == 'outflowAmt') {
          item.type = 'money';
          item.toFixed = '4';
        }
        if (item.key == 'netCashFlowAmt') {
          item.type = 'money';
          item.render = (text, record) => {
            return <strong>{fixedNum(text, 4)}</strong>;
          };
        }
      });
    }

    if (columnsCash) {
      columnsCash.map((item, key) => {
        if (item.key == 'inflowAmt' || item.key == 'outflowAmt') {
          item.type = 'money';
        }
      });
    }

    const searchProps = {
      dataSource: [
        {
          dataIndex: 'portfolioId',
          title: '组合名称',
          type: DATA_ENTRY.PRODUCTGROUPTREE,
          isMultiple: true,
          onRef: (ref) => (this.product = ref),
        },
        {
          dataIndex: ['beginDate', 'endDate'],
          title: '日期区间',
          type: DATA_ENTRY.RANGEDATE,
          initialValue: [moment().add(0, 'day'), moment().add(1, 'year').subtract(1, 'day')],
          hasDataBD: moment().add(0, 'day'),
          disableFuture: false,
          onRef: (ref) => {
            this.RANGEDATE = ref;
          },
          self: this.RANGEDATE,
        },
        {
          dataIndex: 'eventType',
          title: '事件类型',
          type: DATA_ENTRY.TREESELECT,
          isMultiple: true,
          dataSource: selInit,
          initialValue: this.state.checkEventType,
          treeCheckable: true,
        },
        {
          dataIndex: 'weightSetting',
          title: '含权设置',
          type: DATA_ENTRY.SELECT,
          dataSource: selInit2,
          initialValue: riseFallProduct.productId ? '3' : undefined,
        },
      ],
      onQuery: (e) => this.getSearchData(e),
      onClear: (e) => this.onClear(e),
    };
    return (
      <ContentPackage
        title='现金流预测'
        contentHtml={
          <div className={style.bondDeviation}>
            <Row>
              <AdvancedSearch {...searchProps} />
            </Row>
            {this.state.noQuery == true ? (
              <div style={{ marginTop: '13px' }}>
                <NoQueryC />
              </div>
            ) : (
              <div>
                <div style={{ marginTop: '13px' }}>
                  <SecondHeaderC title='区间统计' />
                </div>
                <Row>
                  <Col span={24}>
                    <div className={style.right}>
                      <QuickQueryC
                        dataSource={[
                          { value: 'month', title: '月' },
                          { value: 'quarter', title: '季' },
                          { value: 'year', title: '年' },
                        ]}
                        initialValue={this.state.frequency}
                        disabled={this.state.disabled}
                        onChange={(e) => this.frequencyChange(e)}
                      />
                    </div>
                  </Col>
                </Row>
                <Row style={{ marginTop: '13px' }} gutter={16}>
                  <Col span={12}>
                    <div className={style.bgcolor} style={{ paddingTop: '10px' }}>
                      <XYAxisChartsC
                        series={this.state.series}
                        xAxis={this.state.xAxis}
                        height={400}
                        gridLeft={80}
                        dataZoom={true}
                        type='bar'
                        showBorder={false}
                        width={'100%'}
                        yAxisUnit={['单位(万元)']}
                      />
                    </div>
                  </Col>
                  <Col span={12}>
                    <div className={style.bgcolor} style={{ height: '420px', position: 'relative', padding: '10px' }}>
                      <TableC columns={columns} dataSource={this.state.dataSource} hidePage={true} rowKey='key' />
                      <img src={imgURL} style={{ position: 'absolute', top: '310px', right: '10px' }} />
                    </div>
                  </Col>
                </Row>
                <div style={{ marginTop: '13px' }}>
                  <SecondHeaderC title='现金流明细' />
                </div>
                <div className={style.totalRow} style={{ marginTop: '10px' }}>
                  <Row style={{ marginLeft: '10px' }}>
                    <Col span={1}>
                      <span>汇总&nbsp;:</span>
                    </Col>
                    <Col span={6}>
                      <span style={{ paddingLeft: '20px' }}>现金流流入（万元）&nbsp;&nbsp;{`${accountData.inflowAmt}`}</span>
                      <span className={style.shuxian}>
                        <Divider type='vertical' />
                      </span>
                    </Col>
                    <Col span={6}>
                      <span style={{ paddingLeft: '20px' }}>现金流流出（万元）&nbsp;&nbsp;{`${accountData.outflowAmt}`}</span>
                    </Col>
                  </Row>
                </div>
                <Row>
                  <Col span={24}>
                    <TableC
                      columns={columnsCash}
                      dataSource={this.state.dataSourceCash}
                      pageSize={this.state.pageSize}
                      current={this.state.current}
                      onShowSizeChange={this.onShowSizeChange}
                      onPageChange={this.onPageChange}
                      rowKey='key'
                    />
                  </Col>
                </Row>
              </div>
            )}
          </div>
        }
      />
    );
  }
}
